<template>
  <view class="user-info-container">
    <view class="header">
      <text class="title">个人信息</text>
    </view>
    
    <view class="user-content">
      <view class="avatar-section">
        <view class="avatar-container">
          <image class="avatar" :src="userInfo.avatar || '/static/icons/chat.png'" mode="aspectFill" @click="chooseAvatar"></image>
          <view class="edit-icon">
            <text>+</text>
          </view>
        </view>
        <text class="avatar-tip">点击更换头像</text>
      </view>
      
      <view class="info-form">
        <!-- 真实姓名 -->
      <view class="info-item">
        <text class="label">真实姓名</text>
        <view class="edit-field" @click="startEditing('nickname')" v-if="editingField !== 'nickname'">
          <text class="value">{{ userInfo.nickname || '未设置' }}</text>
        </view>
        <view class="edit-field" v-else>
          <input type="text" v-model="editingData.nickname" placeholder="请输入真实姓名" />
            <button class="save-btn" @click.stop="saveField('nickname')">完成</button>
            <button class="cancel-btn" @click.stop="cancelEditing">取消</button>
          </view>
        </view>
        
        <!-- 邮箱地址 -->
        <view class="info-item">
          <text class="label">邮箱地址</text>
          <view class="edit-field" @click="startEditing('email')" v-if="editingField !== 'email'">
            <text class="value">{{ userInfo.email || '未设置' }}</text>
          </view>
          <view class="edit-field" v-else>
            <input type="text" v-model="editingData.email" placeholder="请输入邮箱地址" />
            <button class="save-btn" @click.stop="saveField('email')">完成</button>
            <button class="cancel-btn" @click.stop="cancelEditing">取消</button>
          </view>
        </view>
        
        <!-- 手机号 -->
        <view class="info-item">
          <text class="label">手机号</text>
          <view class="edit-field" @click="startEditing('phone')" v-if="editingField !== 'phone'">
            <text class="value">{{ userInfo.phone || '未设置' }}</text>
          </view>
          <view class="edit-field" v-else>
            <input type="text" v-model="editingData.phone" placeholder="请输入手机号" />
            <button class="save-btn" @click.stop="saveField('phone')">完成</button>
            <button class="cancel-btn" @click.stop="cancelEditing">取消</button>
          </view>
        </view>
        
        <!-- 年龄 -->
        <view class="info-item">
          <text class="label">年龄</text>
          <view class="edit-field" @click="startEditing('age')" v-if="editingField !== 'age'">
            <text class="value">{{ userInfo.age || '未设置' }}</text>
          </view>
          <view class="edit-field" v-else>
            <input type="number" v-model.number="editingData.age" placeholder="请输入年龄" min="0" max="120" />
            <button class="save-btn" @click.stop="saveField('age')">完成</button>
            <button class="cancel-btn" @click.stop="cancelEditing">取消</button>
          </view>
        </view>
      </view>
      
      <view class="action-section">
        <button class="change-password-btn" @click="changePassword">修改密码</button>
        <button class="logout-btn" @click="logout" type="warn">退出登录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { api } from '@/api';
import { storageAsync, navigateUtil } from '@/utils';

const userInfo = ref({
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  age: ''
});

// 编辑状态管理
const editingField = ref(''); // 当前正在编辑的字段
const editingData = reactive({
  nickname: '',
  email: '',
  phone: '',
  age: ''
});

// 获取用户信息
const getUserInfo = async () => {
  console.log('开始获取用户信息...');
  try {
    // 先从本地存储获取
    console.log('1. 尝试从本地存储获取用户信息');
    const localUserInfo = await storageAsync.get('userInfo');
    if (localUserInfo) {
      console.log('2. 从本地存储获取到用户信息:', localUserInfo);
      userInfo.value = { ...localUserInfo };
    } else {
      console.log('2. 本地存储中没有用户信息');
    }
    
    // 再从服务器获取最新信息
    console.log('3. 开始调用API从服务器获取最新用户信息');
    console.log('3.1 检查api.auth是否存在:', !!api.auth);
    console.log('3.2 检查api.auth.getUserInfo是否为函数:', typeof api.auth.getUserInfo === 'function');
    
    const res = await api.auth.getUserInfo();
    console.log('4. 成功获取到服务器返回的用户信息:', res);
    
    // 确保res.data存在
    if (res && res.data) {
      console.log('5. 更新本地用户信息状态');
      userInfo.value = { ...userInfo.value, ...res.data };
      
      // 更新本地存储
      console.log('6. 更新本地存储中的用户信息');
      await storageAsync.set('userInfo', userInfo.value);
      console.log('7. 用户信息获取和更新完成');
    } else {
      console.warn('5. 服务器返回的数据格式不正确，没有data字段:', res);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    console.error('错误详情:', JSON.stringify(error));
    // 显示友好的错误提示
    uni.showToast({
      title: '获取用户信息失败，请检查网络或稍后重试',
      icon: 'none',
      duration: 3000
    });
  }
};

// 选择头像
const chooseAvatar = async () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      try {
        // 上传头像（这里简化处理，实际应该调用上传接口）
        // const uploadRes = await api.auth.uploadAvatar({ file: tempFilePath });
        // userInfo.value.avatar = uploadRes.data.url;
        
        // 临时使用本地路径
        userInfo.value.avatar = tempFilePath;
        
        // 调用更新接口保存头像
        await updateUserField('avatar', tempFilePath);
        
        uni.showToast({ title: '头像更新成功', icon: 'success' });
      } catch (error) {
        console.error('上传头像失败', error);
        uni.showToast({ title: '上传失败', icon: 'none' });
      }
    }
  });
};

// 开始编辑字段
const startEditing = (field) => {
  editingField.value = field;
  // 复制当前值到编辑数据
  editingData[field] = userInfo.value[field] || '';
};

// 取消编辑
const cancelEditing = () => {
  editingField.value = '';
};

// 保存单个字段
const saveField = async (field) => {
  try {
    // 验证字段
    if (!validateField(field, editingData[field])) {
      return;
    }
    
    // 显示确认对话框
    uni.showModal({
      title: '确认修改',
      content: '确定要修改此字段吗？',
      success: async (res) => {
        if (res.confirm) {
          // 用户确认修改，调用接口
          await updateUserField(field, editingData[field]);
          
          // 更新userInfo
          userInfo.value[field] = editingData[field];
          
          // 更新本地存储
          await storageAsync.set('userInfo', userInfo.value);
          
          uni.showToast({ title: '修改成功', icon: 'success' });
          editingField.value = '';
        }
        // 如果用户取消，不做任何操作
      }
    });
  } catch (error) {
    console.error('保存失败:', error);
    uni.showToast({ title: '修改失败', icon: 'none' });
  }
};

// 验证字段
const validateField = (field, value) => {
  // 对于数字类型的年龄字段，特殊处理空值检查
  if (field === 'age') {
    if (value === null || value === undefined || value === '') {
      uni.showToast({ title: '内容不能为空', icon: 'none' });
      return false;
    }
  } else {
    // 对于字符串类型的字段，使用trim()方法
    if (!value || (typeof value === 'string' && value.trim() === '')) {
      uni.showToast({ title: '内容不能为空', icon: 'none' });
      return false;
    }
  }
  
  if (field === 'email') {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(value)) {
      uni.showToast({ title: '请输入有效的邮箱地址', icon: 'none' });
      return false;
    }
  }
  
  if (field === 'phone') {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(value)) {
      uni.showToast({ title: '请输入有效的手机号', icon: 'none' });
      return false;
    }
  }
  
  if (field === 'age') {
    const age = parseInt(value);
    if (isNaN(age) || age < 0 || age > 120) {
      uni.showToast({ title: '请输入有效的年龄(0-120)', icon: 'none' });
      return false;
    }
  }
  
  return true;
};

// 更新用户字段到服务器
const updateUserField = async (field, value) => {
  const params = {};
  params[field] = value;
  await api.auth.updateUserInfo(params);
};

// 年级选择器已删除

// 修改密码
const changePassword = () => {
  uni.navigateTo({
    url: '/pages/login/changePassword'
  });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: '退出登录',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        console.log('用户确认退出登录');
        
        try {
          // 先获取token
          console.log('获取token用于退出登录接口调用');
          const token = await storageAsync.get('token');
          
          // 调用退出登录接口
          if (token) {
            console.log('调用退出登录接口');
            await api.auth.logout(token);
            console.log('退出登录接口调用成功');
          } else {
            console.log('本地没有token，跳过退出登录接口调用');
          }
          
          // 清除本地存储的登录信息
          console.log('开始清除本地存储的登录信息');
          await storageAsync.remove('token');
          console.log('token已清除');
          await storageAsync.remove('userInfo');
          console.log('userInfo已清除');
          
          // 跳转到登录页面
          console.log('执行跳转到登录页面');
          // 使用uni.reLaunch直接跳转，不通过navigateUtil
          uni.reLaunch({
            url: '/pages/login/login',
            success: () => {
              console.log('成功跳转到登录页面');
            },
            fail: (err) => {
              console.error('跳转失败:', err);
              // 如果reLaunch失败，尝试使用replace
              uni.redirectTo({
                url: '/pages/login/login',
                fail: (redirectErr) => {
                  console.error('redirectTo也失败:', redirectErr);
                }
              });
            }
          });
        } catch (error) {
          console.error('退出登录过程中出现错误:', error);
          
          // 即使出错，也清除本地数据并跳转
          try {
            await storageAsync.remove('token');
            await storageAsync.remove('userInfo');
            uni.reLaunch({
              url: '/pages/login/login'
            });
          } catch (cleanupError) {
            console.error('清除本地数据失败:', cleanupError);
          }
        }
      } else {
        console.log('用户取消退出登录');
      }
    }
  });
};

onMounted(() => {
  console.log('===== userInfo页面组件已挂载，准备获取用户信息 =====');
  getUserInfo();
});

// 导出uni-app页面生命周期钩子
// 在uni-app中，页面生命周期需要通过export default的方式定义
defineExpose({
  onShow: function() {
    console.log('===== userInfo页面已显示，获取最新用户信息 =====');
    getUserInfo();
  }
});
</script>

<style scoped>
.user-info-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
  position: relative;
  overflow: hidden;
}

/* 背景装饰气泡 */
.user-info-container::before,
.user-info-container::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  opacity: 0.4;
  z-index: 0;
}

.user-info-container::before {
  width: 600rpx;
  height: 600rpx;
  background-color: var(--primary-light);
  top: -200rpx;
  right: -200rpx;
  animation: float 8s ease-in-out infinite;
}

.user-info-container::after {
  width: 400rpx;
  height: 400rpx;
  background-color: var(--secondary-light);
  bottom: -150rpx;
  left: -150rpx;
  animation: float 6s ease-in-out infinite reverse;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 140rpx;
  border-bottom: 1rpx solid var(--border-color);
  background-color: white;
  padding: 0 40rpx;
  padding-top: 60rpx;
  box-shadow: 0 2px 12px rgba(255, 133, 162, 0.1);
  z-index: 1;
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: var(--primary-color);
  text-shadow: 0 2px 4px rgba(255, 133, 162, 0.2);
}

.user-content {
  flex: 1;
  padding: 50rpx 40rpx;
  z-index: 1;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-container {
  position: relative;
  margin-bottom: 10rpx;
  animation: pulse 3s ease-in-out infinite;
}

.avatar {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background-color: var(--border-light);
  border: 5rpx solid var(--primary-color);
  box-shadow: 0 6px 16px rgba(255, 133, 162, 0.2);
  transition: all 0.3s ease-in-out;
}

.avatar:active {
  transform: scale(1.05);
  box-shadow: 0 8px 20px rgba(255, 133, 162, 0.3);
}

.edit-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  border: 4rpx solid white;
  box-shadow: 0 4px 12px rgba(255, 133, 162, 0.3);
  transition: all 0.3s ease-in-out;
  animation: bounce 2s ease-in-out infinite;
}

.edit-icon:active {
  transform: scale(1.1);
  background-color: var(--primary-dark);
}

.avatar-tip {
  font-size: 28rpx;
  color: var(--text-secondary);
  font-weight: 500;
}

.info-form {
  background-color: white;
  border-radius: 32rpx;
  padding: 0 40rpx;
  margin-bottom: 50rpx;
  box-shadow: 0 8px 24px rgba(255, 133, 162, 0.1);
  backdrop-filter: blur(10px);
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120rpx;
  border-bottom: 1rpx solid var(--border-color);
  transition: all 0.3s ease-in-out;
}

.info-item:active {
  background-color: var(--border-light);
}

.edit-field {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10rpx 0;
  flex: 1;
  transition: all 0.3s ease-in-out;
}

/* 可点击的信息文本样式 */
.edit-field .value {
  color: var(--text-primary);
  font-size: 32rpx;
  padding: 10rpx 0;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  position: relative;
}

.edit-field .value::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2rpx;
  background-color: var(--primary-color);
  transition: width 0.3s ease-in-out;
}

.edit-field .value:active {
  color: var(--primary-color);
}

.edit-field .value:active::after {
  width: 100%;
}

.edit-field .value:active {
  color: #4A90E2;
}

/* 编辑状态下的输入框样式 */
.edit-field input {
  flex: 1;
  text-align: right;
  font-size: 32rpx;
  color: var(--text-primary);
  padding: 10rpx 0;
  border-bottom: 1rpx solid var(--primary-color);
  background: none;
  transition: all 0.3s ease-in-out;
}

.edit-field input:disabled {
  background-color: transparent;
  color: #999;
  border-bottom: none;
}

.edit-btn, .save-btn, .cancel-btn {
  padding: 12rpx 32rpx;
  font-size: 28rpx;
  border-radius: 32rpx;
  margin-left: 20rpx;
  transition: all 0.3s ease-in-out;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.05);
}

.edit-btn {
  background-color: #f0f0f0;
  color: #666;
}

.save-btn {
  background-color: var(--primary-color);
  color: white;
  font-weight: 600;
  box-shadow: 0 3px 12px rgba(255, 133, 162, 0.3);
  animation: pulse 2s ease-in-out infinite;
}

.save-btn:active {
  background-color: var(--primary-dark);
  transform: scale(0.95);
}

.cancel-btn {
  background-color: var(--border-light);
  color: var(--text-secondary);
}

.cancel-btn:active {
  background-color: var(--border-color);
}

/* 年级选择器样式 */
.grade-value-container {
  display: flex;
  align-items: center;
  color: #333;
  font-size: 32rpx;
  padding: 10rpx 0;
}

.gender-selector.editing {
  display: flex;
  align-items: center;
}

.gender-selector.editing .gender-option {
  margin-right: 20rpx;
}

.grade-selector {
  position: relative;
}

.grade-selector .edit-btn,
.grade-selector .save-btn,
.grade-selector .cancel-btn {
  position: absolute;
  right: 60rpx;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 32rpx;
  color: var(--text-secondary);
  font-weight: 500;
}

.info-item input {
  flex: 1;
  text-align: right;
  font-size: 32rpx;
  color: #333;
  padding: 0;
  border: none;
}

.value {
  font-size: 32rpx;
  color: var(--text-primary);
  font-weight: 500;
}

.gender-selector {
  display: flex;
  gap: 30rpx;
}

.gender-option {
  display: flex;
  align-items: center;
  padding: 10rpx 30rpx;
  border: 2rpx solid #ddd;
  border-radius: 30rpx;
  position: relative;
}

.gender-option.selected {
  border-color: #4A90E2;
  color: #4A90E2;
}

.gender-text {
  font-size: 32rpx;
}

.check-icon {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #4A90E2;
  margin-left: 10rpx;
}

.grade-selector {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 32rpx;
}

.arrow {
  margin-left: 20rpx;
  font-size: 36rpx;
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 36rpx;
}

.change-password-btn,
.logout-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  border-radius: 48rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.3s ease-in-out;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.change-password-btn {
  background-color: white;
  color: var(--primary-color);
  border: 2rpx solid var(--primary-color);
  box-shadow: 0 4px 16px rgba(255, 133, 162, 0.15);
  transition: all 0.3s ease-in-out;
}

.change-password-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 133, 162, 0.1), transparent);
  transition: all 0.5s ease-in-out;
  z-index: -1;
}

.change-password-btn:active {
  transform: translateY(2px);
  box-shadow: 0 2px 10px rgba(255, 133, 162, 0.2);
  background-color: var(--primary-light);
}

.change-password-btn:active::before {
  left: 100%;
}

.logout-btn {
  background-color: white;
  color: #FF5277;
  border: 2rpx solid #FF5277;
  box-shadow: 0 4px 16px rgba(255, 82, 119, 0.15);
  transition: all 0.3s ease-in-out;
  animation: heartbeat 2.5s ease-in-out infinite;
}

.logout-btn:active {
  transform: translateY(2px);
  box-shadow: 0 2px 10px rgba(255, 82, 119, 0.2);
  background-color: #FFF0F3;
}
</style>